package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private JedisPool jedisPool;

    //添加新的检查套餐
    @Override
    public void addNewSetMeal(Setmeal setmeal, Integer[] checkgroupIds) {
        //1.在检查套餐表中,添加新的检查套餐
        setMealDao.add(setmeal);//调用该方法之后setmeal对象的id属性会被赋值

        //将图片信息保存到redis中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

        Integer setmealId = setmeal.getId();
        //2.在中间表中添加新的关联关系
        this.setCheckGroupAndSetMeal(setmealId,checkgroupIds);
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用分页工具
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setMealDao.findByCondition(queryString);

//        System.out.println("setMealServiceImpl---" + page.getTotal());
        return new PageResult(page.getTotal(),page.getResult());
//        return page;
    }

    //在检查组合检查套餐的中间表中添加中间关系
    public void setCheckGroupAndSetMeal(Integer setmealId,Integer[] checkgroupIds){

        if (checkgroupIds != null && checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<String, Integer>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);

                setMealDao.addNewCheckGroupAndSetMeal(map);
            }
        }
    }

    //查询所有的套餐信息
    public List<Setmeal> getSetMeal(){

        return setMealDao.getSetMeal();
    }

    //根据id 查询所有的套餐
    @Override
    public Setmeal findById(Integer id) {
        //1.先查询套餐的基本信息
        Setmeal setmeal = setMealDao.findById(id);

        return setmeal;
    }

    //查询套餐名称及数量
    @Override
    public List<Map<String, Object>> findSetmealCount() {

        List<Map<String, Object>> setmealCount = setMealDao.findSetmealCount();
        return setmealCount;
    }


}
